﻿using CustomControls.PoptipCtr.Base;
using LogProjectManager;
using MyAppProjectControl.BaseViewModels;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CustomControls.PoptipCtr;
using CommonBase;
using System.Windows;
using Newtonsoft.Json;
using CommonBase.ResponseBase;
using static System.Net.WebRequestMethods;

namespace MyAppProjectControl.ViewModels
{
    public class DialogByUplodFileViewModel : IDalogViewModelBase, ILayDialogWindowAware
    {
        public new event Action<ILayDialogResult> RequestClose;

        private int _versionFirstIndex ;

        public int versionFirstIndex
        {
            get
            {
                return _versionFirstIndex;
            }
            set
            {
                SetProperty(ref _versionFirstIndex, value);
            }
        }

        private int _versionSecondIndex;

        public int versionSecondIndex
        {
            get
            {
                return _versionSecondIndex;
            }
            set
            {
                SetProperty(ref _versionSecondIndex, value);
            }
        }
        private int _versionThreeIndex;

        public int versionThreeIndex
        {
            get
            {
                return _versionThreeIndex;
            }
            set
            {
                SetProperty(ref _versionThreeIndex, value);
            }
        }

        private int _versionFourIndex;

        public int versionFourIndex
        {
            get
            {
                return _versionFourIndex;
            }
            set
            {
                SetProperty(ref _versionFourIndex, value);
            }
        }

        private string _filePath="";

        public string filePath
        {
            get
            {
                return _filePath;
            }
            set
            {
                SetProperty(ref _filePath, value);
            }
        }

        private Visibility _IsLodingShow = Visibility.Collapsed;

        public Visibility IsLodingShow
        {
            get
            {
                return _IsLodingShow;
            }
            set
            {
                SetProperty(ref _IsLodingShow, value);
            }
        }


        private string DeviceId { set; get; }

        public new bool CanCloseDialog()
        {
            return true;
        }

        #region cmd
        private DelegateCommand _CloseCommand;
        public DelegateCommand CloseCommand =>
            _CloseCommand ?? (_CloseCommand = new DelegateCommand(CloseCommandMethod));

        private DelegateCommand _InputFileCommand;
        public DelegateCommand InputFileCommand =>
            _InputFileCommand ?? (_InputFileCommand = new DelegateCommand(InputFileCommandMethod));


        private DelegateCommand _OKCommand;
        public DelegateCommand OKCommand =>
            _OKCommand ?? (_OKCommand = new DelegateCommand(OKCommandMethod));

        #endregion

        public new void OnDialogClosed()
        {

        }

        public void OnDialogOpened(ILayDialogParameter parameters)
        {
            try
            {
                DeviceId = parameters.GetValue<string>("deviceid");
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "OnDialogOpened", ex.Message);
            }
        }

        private void CloseCommandMethod()
        {
            RequestClose?.Invoke(null);
           
        }

        private void InputFileCommandMethod()
        {
            try
            {
                System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                openFileDialog.Multiselect = false;
                openFileDialog.Filter = "图片文件(*.rar,*.zip,*.7z)|*.zip;*.rar;*.7z";
                if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string files = openFileDialog.FileName;
                    filePath = files;                  
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "InputFileCommandMethod", ex.ToString());
            }
        }


        private async void UplodFile(string _filePath,string _deviceid,int version_first,int version_second,int version_three,int version_four)
        {
            CommonStaticModel.LastCmdType = "上传版本命令";
            string strMsg = "";
            await Task.Run(async () => {
                try
                {
                    var httpClient = new HttpClient();

                    var url = $"http://192.168.0.41:8081/api/UploadFile/UploadFileAsync?_deviceid={_deviceid}&_version_first={version_first}&_version_second={version_second}&_version_three={version_three}&_version_four={version_four}";

                    var formContent = new MultipartFormDataContent();

                   
                    var fileName = System.IO.Path.GetFileName(filePath);
                    string[] itemarry = fileName.Split('.');
                    fileName = version_first.ToString()+"_" + version_second.ToString() + "_" + version_second.ToString() + "_" + version_four.ToString() +"."+ itemarry.LastOrDefault();
                    var fileContent =System.IO.File.ReadAllBytes(filePath);
                    formContent.Add(new ByteArrayContent(fileContent), "files", fileName);
                    // 发送 HTTP POST 请求，并将 multipart 表单数据作为请求体传输
                    var response = httpClient.PostAsync(url, formContent).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        ResponseBody resulRespons = JsonConvert.DeserializeObject<ResponseBody>(responseBody);
                        if (resulRespons.Code == ErrorCode.OK)
                        {
                            strMsg = "上传附件到服务成功!";
                            LogManager.WriteLog(LogTypeEnum.Normal, "UploadFile", $"后台上传：{filePath}成功!");
                        }
                        else 
                        {
                            strMsg = $"上传附件到服务失败,{resulRespons.Data}";
                            LogManager.WriteLog(LogTypeEnum.Exception, "UploadFile", $"后台上传：{filePath}失败,错误码:{response.StatusCode}!");
                        }
                       
                    }
                    else
                    {
                        strMsg = $"上传附件到服务失败!";
                        LogManager.WriteLog(LogTypeEnum.Exception, "UploadFile", $"后台上传：{filePath}失败,错误码:{response.StatusCode}!");
                    }

                }
                catch (Exception ex)
                {
                    strMsg = $"上传附件到服务失败!+{ex.ToString()}";
                    LogManager.WriteLog(LogTypeEnum.Exception, "UploadFile", ex.ToString());
                }
            });

            IsLodingShow = Visibility.Collapsed;
            MessageControl.Warning(strMsg, "RootMessageTooken");
        }

        private void OKCommandMethod()
        {

            try
            {
                if (string.IsNullOrEmpty(filePath)) 
                {
                    MessageControl.Warning("未选择文件!", "RootMessageTooken");
                    return;
                }

                IsLodingShow = Visibility.Visible;
                UplodFile(filePath, DeviceId, versionFirstIndex, versionSecondIndex, versionThreeIndex, versionFourIndex);
            }
            catch (Exception ex) 
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "OKCommandMethod", ex.ToString());
            }
        }




        protected void ShowDialog(bool _isAutoClose = true, bool _IsShowGray = true, string ContentMsg = "正在为您加载...")
        {
            try
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    LayDialogParameter dialogParameter = new LayDialogParameter();
                    dialogParameter.Add("IsAutoClose", _isAutoClose);
                    dialogParameter.Add("IsShowGray", _IsShowGray);
                    dialogParameter.Add("ContentMsg", ContentMsg);
                    dialogParameter.Add("AutoCloseTime", 2000);
                    LayDialogControl.Show(SystemResource.Nav_DialogLodingView, dialogParameter, rest =>
                    {

                    }, SystemResource.Nav_RootDialogTooken);
                }));

            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "ShowDialog", ex.ToString());
            }
        }

        protected void CloseDialog(string token = "")
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    LayDialogControl.CloseAll();
                }
                else
                {
                    LayDialogControl.Close(token);
                }

            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "ShowDialog", ex.ToString());
            }
        }



    }
}
